package com.kelai.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.kelai.common.IRepository;
import com.kelai.domain.AccountEntity;
import com.kelai.domain.CustomerEntity;
import com.kelai.domain.DeviceEntity;
import com.kelai.domain.ErrorMsgEntity;
import com.kelai.dto.WechatTemplateMsg;
import com.kelai.repository.IDeviceRepository;
import com.kelai.service.*;
import com.kelai.utils.BreezeeUtils;
import com.kelai.utils.SystemTool;
import javafx.util.Callback;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 设备实现类
 * Created by luffy on 2017/05/18.
 */
@Service("deviceService")
public class DefaultDeviceService implements IDeviceService {

    private final static Logger logger = LoggerFactory.getLogger(DefaultDeviceService.class);

    private final IDeviceRepository deviceRepository;
    private final JdbcTemplate jdbcTemplate;

    @Resource
    private IAccountService accountService;
    @Resource
    private ICustomerService customerService;
    @Resource
    private IWeChatService weChatService;
    @Resource
    private IDeviceService deviceService;
    @Resource
    private IErrorMsgService errorMsgService;

    @Autowired
    public DefaultDeviceService(IDeviceRepository deviceRepository, JdbcTemplate jdbcTemplate) {
        this.deviceRepository = deviceRepository;
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public IRepository<DeviceEntity> getRepository() {
        return deviceRepository;
    }


    @Override
    public List<DeviceEntity> findDevicesByShops(List<String> shopIds) {
        return deviceRepository.findDevicesByShops(shopIds);
    }


    /**
     * 检查设备状态,若设备出现问题，向相关用户发送微信消息
     */
    @Override
    public void sendAbnormalMsg(){

        logger.info("~~~~~~~~~sendAbnormalMsg 开始~~~~~~~~~~~~~~~");
        DeviceEntity deviceCondition = new DeviceEntity();
        deviceCondition.getProperties().put("status_in_num","1,0");
//        deviceCondition.getProperties().put("code","43DC83A5"); //测试用
        List<DeviceEntity> abnormalDeviceList = deviceService.listAll(deviceCondition);
        Date now = new Date();

        for(DeviceEntity device : abnormalDeviceList){
            String shopId = device.getCustomerId();
            CustomerEntity shop = customerService.findById(shopId);
            Boolean shopEnable = true;
            //开业时间
            if(shop.getOpenDate() != null){
                if(now.compareTo(shop.getOpenDate()) < 0){
                    shopEnable = true;
                }
            }
            //停业时间
            if(shop.getCloseDate() != null){
                if(now.compareTo(shop.getCloseDate()) > 0){
                    shopEnable = false;
                }
            }
            if(shop.getStatus() == null || !Objects.equals(1,shop.getStatus())){
                shopEnable = false;
            }

            if(shopEnable){
                String customerId = device.findCustomerId();
                CustomerEntity condition = new CustomerEntity();
                condition.getProperties().put("id_in",shopId+","+customerId);
                condition.getProperties().put("status", 1);
                condition.getProperties().put("date_busihour", new Date());

                List<CustomerEntity> list = customerService.listAll(condition);
                Set<AccountEntity> accounts = Sets.newConcurrentHashSet();
                for(CustomerEntity item : list){
                    accounts.addAll(item.getAccounts());
                }
                accounts.stream().filter( account -> {
                    if(Objects.equals(2,account.getSource())){
                        return true;
                    }else{
                        return false;
                    }
                }).forEach( account -> {
                    try {
                        String errorMsg = "";
                        String msg1="" , msg2="" , msg3="" ;
                        Integer focus = device.getFocus() == null ? 1 : device.getFocus();
                        Integer energy = device.getVoltage() ==  null ? 5 : device.getVoltage();
                        if(Objects.equals(1,focus)){
                            msg1 = "失焦,";
                        }
                        if(energy <= 10){
                            msg2 = "电量低,";
                        }
                        if(Objects.equals(0,focus) && energy > 10){
                            msg3 = "离线,";
                        }
                        errorMsg = msg1+msg2+msg3;
                        if(errorMsg.length() > 0){
                            errorMsg = errorMsg.substring(0,errorMsg.length()-1);
                        }

                        WechatTemplateMsg templateMsg = new WechatTemplateMsg();
                        //罗帆oFV-bxEtVscQQukmjxRUVRrxjEhM 陈贤火oFV-bxKR7TjbM4kS4t84pxGyTRtk
                        templateMsg.setTouser(account.getWechat());
                        templateMsg.setTemplate_id("HO3Xa6_EqQqNJU0H0rQ9-hNv9V6hqgnWnqr0YzChjoo");
                        templateMsg.setUrl("");
                        TreeMap<String, TreeMap<String, String>> map = Maps.newTreeMap();
//        故障现象：{{performance.DATA}}
//        故障时间：{{time.DATA}}
                        map.put("first", templateMsg.item("尊敬的用户，您好！", ""));
                        map.put("performance", templateMsg.item("门店 ： "+device.getCustomerName()+"，设备 ： "+device.getCode()+" 存在如下问题："+errorMsg+"。请及时处理！", "#173177"));
                        map.put("time", templateMsg.item(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), ""));
                        map.put("remark", templateMsg.item("客服人员联系方式：黄小姐,电话18367890295，18968937570", ""));
                        templateMsg.setData(map);
                        String jsonTempl = JSONObject.toJSONString(templateMsg);

                        ErrorMsgEntity errorMsgEntity = new ErrorMsgEntity();
                        errorMsgEntity.setErrorMsg("门店"+device.getCustomerName()+"设备"+device.getCode()+"存在如下问题:"+errorMsg+"请及时处理。");
                        errorMsgEntity.setSendDateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                        errorMsgEntity.setToUserId(account.getId());
                        errorMsgEntity.setToUserName(account.getName());
                        errorMsgEntity.setToUserPhone(account.getMobile());

                        errorMsgService.saveInfo(errorMsgEntity,(Callback<ErrorMsgEntity, Object>) param -> {
                            String uuid = SystemTool.uuid();
                            param.setId(uuid);
                            param.setCode(uuid);
                            param.setName(uuid);
                            return null;
                        });

                        try {
                            weChatService.sendTemplate(jsonTempl);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Thread.currentThread().sleep(100);//毫秒
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            }
        }
        logger.info("~~~~~~~~~sendAbnormalMsg 结束~~~~~~~~~~~~~~~");

    }

}
